<?php

namespace app\admin\controller;

use app\common\controller\Backend;

use app\admin\model\Config;


/**
 * 系统配置
 *
 * @icon fa fa-gears
 */
class Configs extends Backend
{
    protected $branch = 0;	// 0：插件市场版，1：自主授权版

    protected $model = null;
    protected $noNeedRight = ['*'];
    protected $app_id = 1;

    public function _initialize()
    {
        parent::_initialize();

        $this->view->assign("VP_BRANCH", $this->branch);
    }

    /**
     * 编辑
     */
    public function index()
    {
        $AppModel = new Config();
        $app = $AppModel->find($this->app_id);

        // 首次进入，默认创建App
        if(empty($app)){
            $AppModel->save(['id'=>$this->app_id,'sitename'=>'哇哇来购']);
            $app = $AppModel->find($this->app_id);
        }

        $this->view->assign("datas", ['config' => $app]);

        return $this->view->fetch();
    }

    // 保存
    public function edit($ids = NULL){
        $AppModel = new Config();
        $app = $AppModel->find($this->app_id);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'trim');

            if($this->branch==1){
                if(empty($params['vpkey'])){
                    $this->error('请填写授权KEY');
                }

            }

            if ($params) {
                // 应用配置空，新增；不空，更新
                if(empty($app)){
                    $AppModel->save($params);
                }else{
                    $AppModel->save($params,['id' => $app['id']]);
                }

                $this->success();

            }else{
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }

    }


    // 插件配置
    public function plugin(){
        $name = $this->request->get('name');

        if ($name == 'oss') {
            $config = config('addons.hooks');
            if (isset($config['upload_config_init']) && $config['upload_config_init']) {
                $availableArr = array_intersect($config['upload_config_init'], ['alioss', 'bos', 'cos', 'upyun', 'ucloud', 'hwobs', 'qiniu']);
                if ($availableArr) {
                    $name = reset($availableArr);
                }
            }
            if (!$name || $name == 'oss') {
                $this->error("请在插件管理中安装一款云存储插件", "");
            }
        } else {
            $info = get_addon_info($name);
            $addonArr = [
                'epay'   => '微信支付宝整合'
            ];
            if (!$info) {
                $this->error('请检查对应插件' . (isset($addonArr[$name]) ? "《{$addonArr[$name]}》" : "") . '是否安装且启动', "");
            }
        }
        $this->redirect('addon/config?name=' . $name . '&dialog=1');
    }

}